package com.niu.utils;

import com.niu.config.MyJwtProperties;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @Author 鹅鹅鹅
 * @Version 1.0.0
 * @Date 2025/7/17 18:26
 * @Description JWT 令牌的生成与解析工具类
 */
@Component
public class MyJwtUtils {

    @Autowired
    private MyJwtProperties properties;

    // 生成令牌
    public String createJWT(Map<String, Object> map){
        String jwt = Jwts.builder()
                .setClaims(map) // 设置数据
                .signWith(SignatureAlgorithm.valueOf(properties.getSignatureType()), properties.getKey()) // 设置签名类型和密钥
                .setExpiration(new Date(System.currentTimeMillis() + properties.getTime())) // 设置有效时间
                .compact();
        return jwt;
    }

    // 解析令牌
    public Map<String, Object> parseJWT(String jwt){
        Claims body = null;
        try {
            body = Jwts.parser()
                    .setSigningKey(properties.getKey())
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
        }
        return body;
    }

}
